<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/17
 * Time: 10:14
 */

namespace app\index\controller;

use app\admin\model\MemberCook;
use app\admin\model\MemberWaiter;
use app\index\model\Member;
use app\index\model\MemberBalanceInfo;
use app\index\model\MemberCash;
use app\index\model\Order;
use app\index\model\ShopEvaluate;
use app\index\model\WxSet;
use think\facade\Cache;

class MemberController extends BaseController
{

    //个人中心
    public function userCenter(){
        $user_id = (int)input('post.user_id');
        $data['user'] = Member::get($user_id);
        $data['order_num'] = Order::where('user_id',$user_id)->count();
        if (!$data['user']){
            return json(['code'=>0,'msg'=>'用户不存在']);
        }
        if (!strstr($data['user']['wx_image'],'https')){
            $data['user']['wx_image']= $this->url.$data['user']['wx_image'];
        }
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data]);
    }
    //获取余额明细
    public function balanceInfo(){
        $user_id = (int)input('post.user_id');
        $where = (int)input('post.status')?['status'=>(int)input('post.status')]:'';
        $page = (int)input('post.page');
        $number = (int)input('post.number');
        $data = MemberBalanceInfo::where('user_id',$user_id)->where($where)->limit(($page - 1) * $number,$number)->select();
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data]);
    }





    //判断用户是否存在
    public function userIf(){
        $user_id = (int)input('post.user_id');
        $ret =  Member::get($user_id);
        if (!$ret){
            return json(['code'=>0,'msg'=>'用户不存在']);
        }
        return json(['code'=>1,'msg'=>'用户存在']);
    }

    //修改用户信息
    public function userUpData(Member $member){
        $post = input('post.');
        $where = ['id'=>$post['user_id']];
        $data = [
            'wx_nickname'=>$post['wx_nickname'],
            'wx_image'=>$post['wx_image'],
            'true_name'=>$post['true_name'],
            'sex'=>$post['sex'],
            'phone'=>$post['phone'],
        ];
        $member->save($data,$where);
        return json(['code'=>1,'msg'=>'更新成功']);
    }
    //上传头像
    public function uploadImg(){
        $file = request()->file('img');
        $ret = $this->upload($file);
        if($ret){
            return json(['code'=>1,'msg'=>'上传成功','data'=>$ret]);
        }else{
            return json(['code'=>1,'msg'=>'上传失败']);
        }
    }
    //获取openID
    public function codeSession(){
        $code = input('post.code');
        $pid = input('post.code')?input('post.code'):0;
        $wx = WxSet::get(1);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$wx['appID']."&secret=".$wx['secret']."&js_code=".$code."&grant_type=authorization_code";
        $ret = $this->curl($url);
        if (array_key_exists('session_key',$ret)){
            Cache::store('redis')->set($ret['openid'],$ret['session_key'],0);
            $uid = $this->user($ret['openid'],$pid);
            return json(['code'=>1,'msg'=>'获取成功','user_id'=>$uid]);
        }else{
            return json($ret);
        }
    }
    //新增用户
    private function user($openid,$pid){
        $ret = Member::where('openID',$openid)->find();
        if ($ret){
            return $ret['id'];
        }else{
            $ret = Member::create(['openID'=>$openid,'pid'=>$pid]);
            return $ret->id;
        }
    }

    //首次加载更新用户数据
    public function userSave(Member $member){
        $data = input('post.');
        $where = ['id'=>$data['user_id']];
        $ret = $member->get($data['user_id']);
        if ($ret['pid'] == 0){
            $upData = [
                'pid'=>$data['pid'],
                'wx_image'=>$data['avatarUrl'],
                'sex'=>$data['gender'],
                'wx_nickname'=>$data['nickName'],
            ];
        }else{
            $upData = [
                'wx_image'=>$data['avatarUrl'],
                'sex'=>$data['gender'],
                'wx_nickname'=>$data['nickName'],
            ];
        }
        $member->save($upData,$where);
        return json(['code'=>1,'msg'=>'更新成功']);
    }


    //我的评论列表
    public function memberEvaluate(){
        $user_id = (int)input('post.user_id');
        $status = input('post.status')?['status'=>(int)input('post.status')]:'';
        $page = (int)input('post.page');
        $number = (int)input('post.number');
        $data['data'] = ShopEvaluate::with(['shop'=>function($query){
            $query->field('id,shop_name,shop_image');
        }])->where('user_id',$user_id)->where($status)->limit(($page - 1) * $number,$number)->select()
            ->each(function ($item){
                if ($item->shop){
                    if (!strstr($item->shop->shop_image,'https')){
                    $item->shop->shop_image = $this->url.$item->shop->shop_image;
                    }
                }
                if ($item->imgs){
                    $ret = explode(',',$item->imgs);
                    foreach ($ret as $k=>$v){
                        $ret[$k] = $this->url.$v;
                    }
                    $item->imgs = $ret;
                }
            })->toArray();
        if (empty($data['data'])){
            return json(['code'=>0,'msg'=>'请求失败']);
        }
        $data['user'] = Member::field('wx_nickname,wx_image')->find($user_id);
        return json(['code'=>1,'msg'=>'请求成功','data'=>$data]);
    }




    //用户提现申请
    public function memberCash(){
        $user_id = (int)input('post.user_id');
        $money   = (float)input('post.money');
        if (!$user_id){
            return json(['code'=>0,'msg'=>'user_id不能为空']);
        }
        if(!$money){
            return json(['code'=>0,'msg'=>'money不能为空']);
        }
        $user = Member::get($user_id);
        if (!$user){
            return json(['code'=>0,'msg'=>'用户不存在']);
        }
        if ($money > (float)$user['balance']){
            return json(['code'=>0,'msg'=>'提现金额不能大于余额']);
        }
        $balance = (float)$user['balance'] - $money;
        $insertData = [
            'user_id'=>$user_id,
            'total'    =>$user['balance'],
            'sum'    =>$money,
            'balance'    =>$balance,
            'create_time'=>time()
        ];
        $insert = MemberCash::create($insertData);
        $upData = Member::update(['balance'=>$balance],['id'=>$user_id]);
        if ($insert && $upData){
            return json(['code'=>1,'msg'=>'提交成功']);
        }
    }

    //服务员提成列表
    public function waiterList(){
        $user_id = (int)input('post.user_id');
        $time   = input('post.time');
        $page =   (int)input('post.page');
        $number = (int)input('post.number');
        if (!$user_id){
            return json(['code'=>0,'msg'=>'用户ID不能为空']);
        }
        $firstDay = date('Y-m-d', strtotime($time));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        $data = MemberWaiter::where('user_id',$user_id)
            ->whereTime('create_time',[$firstDay,$lastDay])
            ->field('id,order_no,total,number,money,status,create_time')->order('create_time asc')->page($page,$number)->select()->toArray();
        if (!$data){
            return json(['code'=>0,'msg'=>'无数据']);
        }
        $total = [];
        foreach ($data as $k=>$v){
            $total[] = $v['money'];
        }
        $total = array_sum($total);
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data,'total'=>$total]);
    }
    //厨师提成列表
    public function cookList(){
        $user_id = (int)input('post.user_id');
        $time   = input('post.time');
        $page =   (int)input('post.page');
        $number = (int)input('post.number');
        $status = (int)input('post.status');
        if (!$user_id){
            return json(['code'=>0,'msg'=>'用户ID不能为空']);
        }
        $firstDay = date('Y-m-01', strtotime($time));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        $data = MemberCook::where('user_id',$user_id)
            ->whereTime('create_time',[$firstDay,$lastDay])
            ->where('status',$status)
            ->field('id,order_no,food_name,number,money,create_time')->order('create_time asc')->page($page,$number)->select()->toArray();
        if (!$data){
            return json(['code'=>0,'msg'=>'无数据']);
        }
        $total = [];
        $number = [];
        foreach ($data as $k=>$v){
            $total[] = $v['money'];
            $number[] = $v['number'];
        }
        $total = array_sum($total);
        $number = array_sum($number);
        return json(['code'=>1,'msg'=>'返回成功','data'=>$data,'total'=>$total,'number'=>$number]);
    }






}